package admin

import (
	"context"
	"fmt"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/net/goai"
	"net/http"
	"server/internal/model"
	"server/internal/tool"
	"strings"

	"server/api/admin/system"
)

func (c *ControllerSystem) AuthorityRouteList(ctx context.Context, req *system.AuthorityRouteListReq) (res *system.AuthorityRouteListRes, err error) {
	res = new(system.AuthorityRouteListRes)
	openAPi := g.Server().GetOpenApi()
	routes := make([]model.SystemRouteOutput, 0)
	for path, item := range openAPi.Paths {
		if strings.HasPrefix(path, "/system/") {
			continue
		}
		var operation *goai.Operation
		var method string
		if item.Get != nil {
			operation = item.Get
			method = http.MethodGet
		} else if item.Post != nil {
			operation = item.Post
			method = http.MethodPost
		} else {
			g.Log().Infof(ctx, fmt.Sprintf("路由信息异常，跳过处理：%s", path))
			continue
		}
		routes = append(routes, model.SystemRouteOutput{
			Path:        tool.BuildAuthRoute(method, path), //以该格式入库，后续权限检测依据，不能随意修改
			Description: operation.Description,
			Summary:     fmt.Sprintf("%s-%s", operation.Tags, operation.Summary),
			Method:      method,
		})
	}
	res.Routes = routes
	return res, err
}
